package com.mida.bms.report.service.impl;


import com.mida.bms.report.entity.*;
import com.mida.bms.report.mapper.*;
import com.mida.bms.report.service.DocStructTemplateInfoService;
import com.mida.bms.report.service.SoidService;
import com.mida.bms.report.vo.DocStructTemplateAuthBatchVo;
import com.mida.bms.report.vo.DocStructTemplateInfoVo;
import com.mida.bms.report.vo.Page;
import com.mida.bms.report.vo.PageResultVo;

import com.mida.tool.common.result.ActionResult;
import com.mida.tool.common.result.BaseResult;
import com.mida.tool.common.result.ListResult;
import com.mida.tool.common.utils.CharTransFormUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 模版基本信息的业务逻辑实现层
 *
 * @author dj
 */
@Service
@Slf4j
@Transactional
public class DocStructTemplateInfoServiceImpl extends BaseResult implements DocStructTemplateInfoService {

    /**
     * Logger
     */
    private final Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 模版基本信息的Dao
     */
    @Autowired
    private DocStructTemplateInfoMapper docStructTemplateInfoMapper;


    @Autowired
    private SoidService soidService;


    @Autowired
    private DocStructTemplateAuthMapper docStructTemplateAuthMapper;

    @Autowired
    private DocStructTemplateClobContentMapper docStructTemplateClobContentMapper;

    @Autowired
    private DocStructTemplateDiagnosisMapper docStructTemplateDiagnosisMapper;

    @Autowired
    private DocStructTemplateDiseaseMapper docStructTemplateDiseaseMapper;

    @Autowired
    private DocStructTemplatePartsMapper docStructTemplatePartsMapper;

    /**
     * 添加模版基本信息
     *
     * @param docStructTemplateInfoVo
     * @return
     * @throws Exception
     */
    @Override
    public ActionResult addDocStructTemplateInfo(
            DocStructTemplateInfoVo docStructTemplateInfoVo) throws Exception {
        ActionResult actionResult = new ActionResult();
        DocStructTemplateInfo docStructTemplateInfo = setDocStructTemplateInfo(docStructTemplateInfoVo);

        int num = docStructTemplateInfoMapper.getCountName(docStructTemplateInfoVo.getStTemplateName());
        if (num > 0) {
            actionResult.setStatus(HttpStatus.BAD_REQUEST.value());
            actionResult.setMessage("模版名称数据库已经存在");
            return actionResult;
        }

//        Long soid = cmOIDGanerator.getSOID();
        Long soid = soidService.getSoid();
        docStructTemplateInfo.setStTemplateInfoSoid(soid);
        docStructTemplateInfoVo.setStTemplateInfoSoid(soid);
        docStructTemplateInfoMapper.insertSelective(docStructTemplateInfo);

        soidService.insertOid(soid, 4);
//        String oid = cmOIDGanerator.getOID(4);
//        DtOid dtOid = new DtOid();
//        dtOid.setOid(oid);
//        dtOid.setSoid(soid);
//        cmDtOidMapper.insert(dtOid);

        // 诊断标识不为空的场合
        if (docStructTemplateInfoVo != null
                && StringUtils.isNotEmpty(docStructTemplateInfoVo.getDiagnosisSoid())) {
            String strSoid[] = docStructTemplateInfoVo.getDiagnosisSoid().split(",");
            DocStructTemplateDiagnosis docDiagnosis;
            for (String s : strSoid) {
                docDiagnosis = new DocStructTemplateDiagnosis();
                docDiagnosis.setIsDelete(0l);
                docDiagnosis.setCreateDate(new Date());
                docDiagnosis.setDiagnosisSoid(Long.valueOf(s));
//                docDiagnosis.setStructTemplateDiagnosisSoid(cmOIDGanerator.getSOID());
                docDiagnosis.setStructTemplateDiagnosisSoid(soidService.getSoid());
                docDiagnosis.setStTemplateInfoSoid(soid);
                docDiagnosis.setCreator(docStructTemplateInfoVo.getEmployeeSoid());
                docStructTemplateDiagnosisMapper.insertSelective(docDiagnosis);
            }
        }

        // 疾病分类不为空的场合
        if (docStructTemplateInfoVo != null
                && StringUtils.isNotEmpty(docStructTemplateInfoVo.getDiseaseClass())) {
            String strSoid[] = docStructTemplateInfoVo.getDiseaseClass().split(",");
            DocStructTemplateDisease docDisease;
            for (String s : strSoid) {
                docDisease = new DocStructTemplateDisease();
                docDisease.setIsDelete(0l);
                docDisease.setCreateDate(new Date());
                docDisease.setDiseaseClass(Long.valueOf(s));
//                docDisease.setStructTemplateDiseaseSoid(cmOIDGanerator.getSOID());
                docDisease.setStructTemplateDiseaseSoid(soidService.getSoid());
                docDisease.setStTemplateInfoSoid(soid);
                docDisease.setCreator(docStructTemplateInfoVo.getEmployeeSoid());
                docStructTemplateDiseaseMapper.insertSelective(docDisease);
            }
        }

        // 检查部位不为空的场合
        if (docStructTemplateInfoVo != null
                && StringUtils.isNotEmpty(docStructTemplateInfoVo.getExamParts())) {
            String strSoid[] = docStructTemplateInfoVo.getExamParts().split(",");
            DocStructTemplateParts docParts;
            for (String s : strSoid) {
                docParts = new DocStructTemplateParts();
                docParts.setIsDelete(0l);
                docParts.setCreateDate(new Date());
                docParts.setExamParts(Long.valueOf(s));
//                docParts.setStructTemplatePartsSoid(cmOIDGanerator.getSOID());
                docParts.setStructTemplatePartsSoid(soidService.getSoid());
                docParts.setCreator(docStructTemplateInfoVo.getEmployeeSoid());
                docParts.setStTemplateInfoSoid(soid);
                docStructTemplatePartsMapper.insertSelective(docParts);
            }
        }

        if (docStructTemplateInfoVo != null
                && StringUtils.isNotEmpty(docStructTemplateInfoVo.getStTempAuthSoids())) {
            String strSoid[] = docStructTemplateInfoVo.getStTempAuthSoids().split(",");

            DocStructTemplateAuth dsta;
            for (int i = 0; i < strSoid.length; i++) {
                dsta = new DocStructTemplateAuth();
                dsta.setCreateDate(new Date());
                dsta.setStTemplateInfoSoid(soid);
                dsta.setIsDelete(0l);
//                dsta.setStTempAuthSoid(cmOIDGanerator.getSOID());
                dsta.setStTempAuthSoid(soidService.getSoid());
                dsta.setStTempAuthSpSoid(Long.valueOf(strSoid[i]));
                docStructTemplateAuthMapper.insertSelective(dsta);
            }
        }

        buildActionSuccess(actionResult);
        return actionResult;
    }

    /**
     * 更新模版基本信息
     *
     * @param docStructTemplateInfoVo
     * @return
     * @throws Exception
     */
    @Override
    public ActionResult updateDocStructTemplateInfo(
            DocStructTemplateInfoVo docStructTemplateInfoVo) throws Exception {
        ActionResult actionResult = new ActionResult();
        DocStructTemplateInfo docStructTemplateInfo = setDocStructTemplateInfo(docStructTemplateInfoVo);
        DocStructTemplateInfo d =
                docStructTemplateInfoMapper.selectByPrimaryKey(docStructTemplateInfoVo.getStTemplateInfoSoid());

        if (d != null &&
                StringUtils.isNotEmpty(docStructTemplateInfoVo.getStTemplateName())
                && !d.getStTemplateName().equals(docStructTemplateInfoVo.getStTemplateName())) {
            int num = docStructTemplateInfoMapper.getCountName(docStructTemplateInfoVo.getStTemplateName());
            if (num > 0) {
                actionResult.setStatus(HttpStatus.BAD_REQUEST.value());
                actionResult.setMessage("模版名称数据库已经存在");
                return actionResult;
            }
        }

        docStructTemplateInfoMapper.updateByPrimaryKeySelective(docStructTemplateInfo);

        // 诊断标识不为空的场合
        if (docStructTemplateInfoVo != null
                && StringUtils.isNotEmpty(docStructTemplateInfoVo.getDiagnosisSoid())) {
            String strSoid[] = docStructTemplateInfoVo.getDiagnosisSoid().split(",");
            docStructTemplateDiagnosisMapper.deleteById(docStructTemplateInfoVo.getStTemplateInfoSoid());
            DocStructTemplateDiagnosis docDiagnosis;
            for (String s : strSoid) {
                docDiagnosis = new DocStructTemplateDiagnosis();
                docDiagnosis.setIsDelete(0L);
                docDiagnosis.setCreateDate(new Date());
                docDiagnosis.setUpdateDate(new Date());
                docDiagnosis.setDiagnosisSoid(Long.valueOf(s));
//                docDiagnosis.setStructTemplateDiagnosisSoid(cmOIDGanerator.getSOID());
                docDiagnosis.setStructTemplateDiagnosisSoid(soidService.getSoid());
                docDiagnosis.setStTemplateInfoSoid(docStructTemplateInfoVo.getStTemplateInfoSoid());
                docDiagnosis.setCreator(docStructTemplateInfoVo.getEmployeeSoid());
                docDiagnosis.setUpdateUser(docStructTemplateInfoVo.getEmployeeSoid());
                docStructTemplateDiagnosisMapper.insertSelective(docDiagnosis);
            }
        }

        // 疾病分类不为空的场合
        if (docStructTemplateInfoVo != null
                && StringUtils.isNotEmpty(docStructTemplateInfoVo.getDiseaseClass())) {
            String strSoid[] = docStructTemplateInfoVo.getDiseaseClass().split(",");
            docStructTemplateDiseaseMapper.deleteById(docStructTemplateInfoVo.getStTemplateInfoSoid());
            DocStructTemplateDisease docDisease;
            for (String s : strSoid) {
                docDisease = new DocStructTemplateDisease();
                docDisease.setIsDelete(0L);
                docDisease.setCreateDate(new Date());
                docDisease.setUpdateDate(new Date());
                docDisease.setDiseaseClass(Long.valueOf(s));
//                docDisease.setStructTemplateDiseaseSoid(cmOIDGanerator.getSOID());
                docDisease.setStructTemplateDiseaseSoid(soidService.getSoid());
                docDisease.setStTemplateInfoSoid(docStructTemplateInfoVo.getStTemplateInfoSoid());
                docDisease.setCreator(docStructTemplateInfoVo.getEmployeeSoid());
                docDisease.setUpdateUser(docStructTemplateInfoVo.getEmployeeSoid());
                docStructTemplateDiseaseMapper.insertSelective(docDisease);
            }
        }

        // 检查部位不为空的场合
        if (docStructTemplateInfoVo != null
                && StringUtils.isNotEmpty(docStructTemplateInfoVo.getExamParts())) {
            String strSoid[] = docStructTemplateInfoVo.getExamParts().split(",");
            docStructTemplatePartsMapper.deleteById(docStructTemplateInfoVo.getStTemplateInfoSoid());
            DocStructTemplateParts docParts;
            for (String s : strSoid) {
                docParts = new DocStructTemplateParts();
                docParts.setIsDelete(0L);
                docParts.setCreateDate(new Date());
                docParts.setUpdateDate(new Date());
                docParts.setExamParts(Long.valueOf(s));
//                docParts.setStructTemplatePartsSoid(cmOIDGanerator.getSOID());
                docParts.setStructTemplatePartsSoid(soidService.getSoid());
                docParts.setStTemplateInfoSoid(docStructTemplateInfoVo.getStTemplateInfoSoid());
                docParts.setCreator(docStructTemplateInfoVo.getEmployeeSoid());
                docParts.setUpdateUser(docStructTemplateInfoVo.getEmployeeSoid());
                docStructTemplatePartsMapper.insertSelective(docParts);
            }
        }


        if (docStructTemplateInfoVo != null
                && StringUtils.isNotEmpty(docStructTemplateInfoVo.getStTempAuthSoids())) {
            String strSoid[] = docStructTemplateInfoVo.getStTempAuthSoids().split(",");

            List<Long> list =
                    docStructTemplateAuthMapper.selectByStTemplateInfoSoid(
                            docStructTemplateInfoVo.getStTemplateInfoSoid());

            if (list.size() > 0) {
                docStructTemplateAuthMapper.deleteById(docStructTemplateInfoVo.getStTemplateInfoSoid());
            }

            DocStructTemplateAuth dsta;
            for (int i = 0; i < strSoid.length; i++) {
                dsta = new DocStructTemplateAuth();
                dsta.setCreateDate(new Date());
                dsta.setStTemplateInfoSoid(docStructTemplateInfoVo.getStTemplateInfoSoid());
                dsta.setIsDelete(0l);
//                    dsta.setStTempAuthSoid(cmOIDGanerator.getSOID());
                dsta.setStTempAuthSoid(soidService.getSoid());
                dsta.setStTempAuthSpSoid(Long.valueOf(strSoid[i]));
                docStructTemplateAuthMapper.insertSelective(dsta);
            }

        }

        buildActionSuccess(actionResult);
        return actionResult;
    }

    /**
     * 逻辑删除模版基本信息
     *
     * @param stTemplateInfoSoid
     * @return
     * @throws Exception
     */
    @Override
    public ActionResult deleteDocStructTemplateInfo(Long stTemplateInfoSoid) throws Exception {
        ActionResult actionResult = new ActionResult();
        docStructTemplateInfoMapper.deleteByPrimaryKey(stTemplateInfoSoid);
        docStructTemplateClobContentMapper.deleteBystTemplateInfoSoid(stTemplateInfoSoid);
        docStructTemplateAuthMapper.deleteById(stTemplateInfoSoid);
        buildActionSuccess(actionResult);
        return actionResult;
    }

    /**
     * 查询模板分页列表处理
     *
     * @param docStructTemplateInfoVo
     * @return
     */
    @Override
    public PageResultVo<DocStructTemplateInfo> getDocStructTemplateInfoPage(DocStructTemplateInfoVo docStructTemplateInfoVo) throws Exception {

        List<DocStructTemplateInfo> list = new ArrayList<DocStructTemplateInfo>();
        Map<String, Object> mapParm = new HashMap<String, Object>();
        PageResultVo pageResultVo = new PageResultVo();
        Page page = new Page();
        page = new Page(docStructTemplateInfoVo.getCurrentPage(), docStructTemplateInfoVo.getPageSize());

        mapParm.put("seachParm", docStructTemplateInfoVo.getSearchData());
        mapParm.put("list", docStructTemplateInfoVo.getListExamServiceTypeSoid());

        int num = docStructTemplateInfoMapper.findPageCount(mapParm);

        if (num == 0) {
            pageResultVo.setList(null);
            pageResultVo.setPage(null);
        } else {
            page.setTotalCount(num);
            mapParm.put("startIndex", page.getBeginIndex());
            mapParm.put("endIndex", docStructTemplateInfoVo.getCurrentPage() * page.getEveryPage());
            list = docStructTemplateInfoMapper.getDocStructTemplateInfoPage(mapParm);

            pageResultVo.setList(list);
            pageResultVo.setPage(page);
        }
        return pageResultVo;
    }

    /**
     * 根据模板soid查询模版数据
     *
     * @param stTemplateInfoSoid
     * @return
     * @throws Exception
     */
    @Override
    public ListResult getDocStructTemplateInfo(Long stTemplateInfoSoid) throws Exception {

        ListResult result = new ListResult();
        DocStructTemplateInfo docStructTemplateInfo = new DocStructTemplateInfo();
        docStructTemplateInfo = docStructTemplateInfoMapper.selectByPrimaryKey(stTemplateInfoSoid);

        List<Long> list = docStructTemplateAuthMapper.selectByStTemplateInfoSoid(stTemplateInfoSoid);
        List<Long> listDiagnosisSoid
                = docStructTemplateDiagnosisMapper.selectByStTemplateInfoSoid(stTemplateInfoSoid);
        List<Long> listDiseaseSoid
                = docStructTemplateDiseaseMapper.selectByStTemplateInfoSoid(stTemplateInfoSoid);
        List<Long> listPartsSoid
                = docStructTemplatePartsMapper.selectByStTemplateInfoSoid(stTemplateInfoSoid);

        if (docStructTemplateInfo != null) {
            if (list != null && list.size() > 0) {
                String str = "";
                for (int i = 0; i < list.size(); i++) {
                    str += list.get(i);
                    str += ",";
                }

                if (str != null && str.length() > 0) {
                    str = str.substring(0, str.lastIndexOf(","));
                }

                docStructTemplateInfo.setStTempAuthSoids(str);
            }

            List<String> listTmp;
            if (listDiagnosisSoid != null && listDiagnosisSoid.size() > 0) {
                listTmp = new ArrayList<>();
                for (Long tmp : listDiagnosisSoid) {
                    listTmp.add(String.valueOf(tmp));
                }
                docStructTemplateInfo.setDiagnosisSoid(listTmp);
            }

            if (listDiseaseSoid != null && listDiseaseSoid.size() > 0) {
                listTmp = new ArrayList<>();
                for (Long tmp : listDiseaseSoid) {
                    listTmp.add(String.valueOf(tmp));
                }
                docStructTemplateInfo.setDiseaseClass(listTmp);
            }

            if (listPartsSoid != null && listPartsSoid.size() > 0) {
                listTmp = new ArrayList<>();
                for (Long tmp : listPartsSoid) {
                    listTmp.add(String.valueOf(tmp));
                }
                docStructTemplateInfo.setExamParts(listTmp);
            }

        }

        result.setData(docStructTemplateInfo);
        result.setStatus(HttpStatus.OK.value());
        result.setMessage("success");
        return result;
    }

    /**
     * 查询可授权模板列表分页列表处理
     *
     * @param docStructTemplateAuthBatchVo
     * @return
     */
    @Override
    public PageResultVo<DocStructTemplateInfo> getAuthSpaceDocStructTemplateInfoPage(
            DocStructTemplateAuthBatchVo docStructTemplateAuthBatchVo) throws Exception {

        List<DocStructTemplateInfo> list = new ArrayList<DocStructTemplateInfo>();
        Map<String, Object> mapParm = new HashMap<String, Object>();
        PageResultVo pageResultVo = new PageResultVo();
        Page page = new Page();
        page = new Page(docStructTemplateAuthBatchVo.getCurrentPage(), docStructTemplateAuthBatchVo.getPageSize());

        if (StringUtils.isNotEmpty(docStructTemplateAuthBatchVo.getSearchData())) {
            mapParm.put("seachParm", docStructTemplateAuthBatchVo.getSearchData());
        }
        if (docStructTemplateAuthBatchVo.getListExamServiceType() != null &&
                docStructTemplateAuthBatchVo.getListExamServiceType().size() > 0) {
            mapParm.put("listExamServiceType", docStructTemplateAuthBatchVo.getListExamServiceType());
        }

        if (docStructTemplateAuthBatchVo.getStTempAuthSpSoids() != null &&
                docStructTemplateAuthBatchVo.getStTempAuthSpSoids().size() > 0) {
            mapParm.put("list", docStructTemplateAuthBatchVo.getStTempAuthSpSoids());
        }
        int num = docStructTemplateInfoMapper.getCountByAuthSpSoid(mapParm);

        if (num == 0) {
            pageResultVo.setList(null);
            pageResultVo.setPage(null);
        } else {
            page.setTotalCount(num);
            mapParm.put("startIndex", page.getBeginIndex());
            mapParm.put("endIndex", docStructTemplateAuthBatchVo.getCurrentPage() * page.getEveryPage());
            list = docStructTemplateInfoMapper.getDocStructTemplateInfoByAuthSpSoidPage(mapParm);
            pageResultVo.setList(list);
            pageResultVo.setPage(page);
        }
        return pageResultVo;
    }

    /**
     * 查询可授权模板列表处理
     *
     * @param docStructTemplateAuthBatchVo
     * @return
     * @throws Exception
     */
    @Override
    public List<DocStructTemplateInfo> getAuthSpaceDocStructTemplateInfoList(DocStructTemplateAuthBatchVo docStructTemplateAuthBatchVo) throws Exception {

        List<DocStructTemplateInfo> list = new ArrayList<DocStructTemplateInfo>();
        Map<String, Object> mapParm = new HashMap<String, Object>();

        if (docStructTemplateAuthBatchVo.getListExamServiceType() != null &&
                docStructTemplateAuthBatchVo.getListExamServiceType().size() > 0) {
            mapParm.put("listExamServiceType", docStructTemplateAuthBatchVo.getListExamServiceType());
        }

        if (docStructTemplateAuthBatchVo.getStTempAuthSpSoids() != null &&
                docStructTemplateAuthBatchVo.getStTempAuthSpSoids().size() > 0) {
            mapParm.put("list", docStructTemplateAuthBatchVo.getStTempAuthSpSoids());
        }

        list = docStructTemplateInfoMapper.getDocStructTemplateInfoByAuthSpSoidList(mapParm);

        return list;
    }


    /**
     * 设置模板基本信息数据
     *
     * @param docStructTemplateInfoVo
     */
    private DocStructTemplateInfo setDocStructTemplateInfo(
            DocStructTemplateInfoVo docStructTemplateInfoVo) throws Exception {
        DocStructTemplateInfo docStructTemplateInfo = new DocStructTemplateInfo();
        BeanUtils.copyProperties(docStructTemplateInfoVo, docStructTemplateInfo);
        docStructTemplateInfo.setCreateDate(new Date());
        docStructTemplateInfo.setUpdateDate(new Date());
        if (StringUtils.isNotEmpty(docStructTemplateInfoVo.getStTemplateName())) {
            docStructTemplateInfo.setPyCode(
                    CharTransFormUtil.toPinyinSimple(docStructTemplateInfoVo.getStTemplateName()));
            docStructTemplateInfo.setWbCode(
                    CharTransFormUtil.toWubi(docStructTemplateInfoVo.getStTemplateName()));
        }

        docStructTemplateInfo.setIsDelete(0l);
        return docStructTemplateInfo;
    }
}
